package com.example.filesftp.config;

import com.example.filesftp.ftptransfer.domain.entity.FileTransferConfig;
import com.example.filesftp.ftptransfer.service.FileSftpService;

import com.example.filesftp.job.FileTransferJob;

import org.quartz.*;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.List;

@Configuration
public class SchedulerConfig {

    private final Scheduler scheduler;
    private final FileSftpService fileTransferService;

    public SchedulerConfig(Scheduler scheduler, FileSftpService fileTransferService) {
        this.scheduler = scheduler;
        this.fileTransferService = fileTransferService;
    }

    @PostConstruct
    public void init() throws SchedulerException {
        scheduler.clear();
        List<FileTransferConfig> configs = fileTransferService.getAllConfigs();
        for (FileTransferConfig config : configs) {
            if (config.getActive()) {
                scheduleJob(config);
            }
        }
    }

    private void scheduleJob(FileTransferConfig config) throws SchedulerException {
        JobDetail jobDetail = JobBuilder.newJob(FileTransferJob.class)
                .withIdentity(config.getId(), "file-transfer-jobs")
                .usingJobData("configId", config.getId())
                .build();

        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(config.getId() + "-trigger", "file-transfer-triggers")
                .withSchedule(CronScheduleBuilder.cronSchedule(config.getCronExpression()))
                .build();

        scheduler.scheduleJob(jobDetail, trigger);
    }
}